<?php declare(strict_types=1);


namespace App\Controller\Api\Wechat;


use App\Controller\AbstractController;
use App\Service\Api\Wechat\OpenPlatformService;
use App\Utils\Wechat\OpenPlatform\MiniProgram;
use App\Utils\Wechat\OpenPlatform\OpenPlatform;
use App\Utils\Wechat\Payment;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Base\MessageTrait;
use Hyperf\HttpServer\Request;
use Hyperf\Redis\RedisFactory;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\HttpFoundation\Response;


class OpenPlatformController extends AbstractController
{
    /**
     * @Inject()
     * @var OpenPlatform
     */
    private $openPlatform;

    /**
     * @Inject()
     * @var MiniProgram
     */
    private $miniProgram;

    /**
     * @Inject()
     * @var OpenPlatformService
     */
    private $openPlatformService;

    /**
     * @return Response
     * @throws BadRequestException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     */
    public function auth()
    {
//        $data = $this->request->getParsedBody();
//        $signature = $this->request->input('msg_signature');
//        $timestamp = $this->request->input('timestamp');
//        $nonce = $this->request->input('nonce');
//        $account = di(MiniProgram::class)->account($data['AppId']);
//        $content = $account->encryptor->decrypt($data['Encrypt'],$signature, $nonce, $timestamp);
//        $account->customer_service->send([
//
//        ]);
//        di(Redis::class)->set('test', $content);
//        return $this->response->response()->withHeader('content-type', 'text/plain')
//            ->withContent('success');
        $res = di(OpenPlatform::class)->setTicket();
        $appID = config('wechat.open_platform.app_id');
        $ticket = serialize($this->openPlatform->getTicket());
        di(RedisFactory::class)->get('db1')->set('c:easywechat.open_platform.verify_ticket.' . $appID, $ticket);
        return $res;
    }

    /**
     * @param string $appID
     * @return MessageTrait|\Hyperf\HttpMessage\Server\Response
     * @throws RuntimeException
     */
    public function notice(string $appID)
    {
        $data = $this->request->getParsedBody();
        $msgSignature = $this->request->input('msg_signature');
        $nonce = $this->request->input('nonce');
        $timestamp = $this->request->input('timestamp');
        $decryptData = di(MiniProgram::class)->decrypt($appID, $data['Encrypt'], $msgSignature, $nonce, $timestamp);
        $data = $this->openPlatformService->notice($appID, $decryptData);
        if ($data) {
            return $this->response->response()->withHeader('content-type', 'text/plain')->withContent('SUCCESS');
        }
        return $this->response->response()->withContent('error');
    }

    /**
     * @return mixed
     * @throws InvalidConfigException
     * @throws GuzzleException
     */
    public function templateList()
    {
        $res = $this->openPlatform->templateList();
        return $this->response->success($res);
    }


    # ======================== demo =============================== #

    /**
     * @param Request $request
     * @return array|mixed
     * @throws Exception
     */
    public function authCode(Request $request)
    {
        $authCode = $this->request->input('auth_code');
        return $this->openPlatform->handleAuthorize($authCode);
    }

    public function preAuthUrl()
    {
        $callbackUrl = config('wechat.open_platform.pre_auth_url.callback_url');
        return di(OpenPlatform::class)->preAuthUrl($callbackUrl);
    }

    public function info()
    {
        return di(OpenPlatform::class)->authInfo('wx961c2d9582510b92');
    }

    public function getQrCode()
    {
        $appID = $this->request->input('appid');
        return di(MiniProgram::class)->getQrCode($appID);
    }

    /**
     * @return ResponseInterface
     * @throws InvalidConfigException
     */
    public function login()
    {
        $mini = di(MiniProgram::class);
        return $this->response->success($mini->login('wx961c2d9582510b92', $this->request->input('code')));
    }

    /**
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|ResponseInterface|string
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws GuzzleException
     */
    public function pay()
    {
        return di(Payment::class)->prepay(100,Payment::TRADE_TYPE_JSAPI, 'oUtPn5RQwLQ-JChFgzCp0HpxHRqs');
    }
}